package com.cxs.shopstore.config;

import com.cxs.shopstore.interceptors.PreInterceptor;
import com.cxs.shopstore.interceptors.TokenInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/*
 * @Author:cxs
 * @Date:2021/5/11  13:40
 * @Version 1.0
 * WebMvc配置文件
 * */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public TokenInterceptor tokenInterceptor(){
        return new TokenInterceptor();
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "OPTIONS")
                .maxAge(3600);
    }
    /**
     * 添加一个拦截器，用于解决前后端分离跨域问题引起session不一致
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String excludePathPatterns[] = {
                "/css/**",
                "/js/**",
                "/img/**",
                "/font/**",
                "/login.html",
                "/admin.html",
                "/index.html",
                "/iframe/**",
                "/getImgCode",
                "/user/login"};
        registry.addInterceptor(new PreInterceptor())
                .addPathPatterns("/*")
                .excludePathPatterns(excludePathPatterns);

        registry.addInterceptor(tokenInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(excludePathPatterns);
    }


}
